/**
 * schoolBodyReservation.php
 * 
 */


$(document).ready(function() {
	datatablePlugins();
	datatableConfig();
	formFilters();
	//tmp();
});



/**
 * this function is added to the prototype of datatable plugin so we can reload 
 * data from server and use the local search feacture (avoiding this way the use of the server by the search field)
 */
function datatablePlugins() {
	
	$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
	{
	    if ( typeof sNewSource != 'undefined' && sNewSource != null )
	    {
	        oSettings.sAjaxSource = sNewSource;
	    }
	    this.oApi._fnProcessingDisplay( oSettings, true );
	    var that = this;
	    var iStart = oSettings._iDisplayStart;
	    var aData = [];
	 
	    this.oApi._fnServerParams( oSettings, aData );
	     
	    oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
	        /* Clear the old information from the table */
	        that.oApi._fnClearTable( oSettings );
	         
	        /* Got the data - add it to the table */
	        var aData =  (oSettings.sAjaxDataProp !== "") ?
	            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
	         
	        for ( var i=0 ; i<aData.length ; i++ )
	        {
	            that.oApi._fnAddData( oSettings, aData[i] );
	        }
	         
	        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
	        that.fnDraw();
	         
	        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
	        {
	            oSettings._iDisplayStart = iStart;
	            that.fnDraw( false );
	        }
	         
	        that.oApi._fnProcessingDisplay( oSettings, false );
	         
	        /* Callback user function - for event handlers etc */
	        if ( typeof fnCallback == 'function' && fnCallback != null )
	        {
	            fnCallback( oSettings );
	        }
	    }, oSettings );
	};
}



/**
 * Function to config the datatable
 */
function datatableConfig() {
	
	// global 'vars' used to filter content
	offerId = 0;
	reserve = 'all';
	start 	= null;
	end 	= null;

	var oTable = $('#reservationTable');
	
	var reserveInfo = $('#reserveInfo');
	
	// url to retrieve the reserves list
	var serverRequest = ajaxUrl + '/readReservationAction';

	// datatable properties
	var tableProperties = {		
			
		'sAjaxSource': 		serverRequest,	
		'fnServerParams':	function(aoData) {

			// send these POST values
			aoData.push({
				"name":		"offerId",
				"value":	offerId
			});
			aoData.push({
				"name":		"reserve",
				"value":	reserve
			});
			aoData.push({
				"name":		"start",
				"value":	start
			});
			aoData.push({
				"name":		"end",
				"value":	end
			});
		},
		'sServerMethod':	'POST',
		'sAjaxDataProp': 	'data',
		"aoColumns": [
  			{"mDataProp":"clientName"},
  			{"mDataProp":"offerName"},
  			{"mDataProp":"clientEmail"},
  			{"mDataProp":"clientPhone"},
  			{"mDataProp":"clientReserveDate"},
  			{"mDataProp":"company"}
		  ],
		  'oLanguage': {
			'sInfo':		'registo _START_ até ao _END_ de _TOTAL_',
			'sZeroRecords': 'Não existem registos',
			'sSearch':		'Procurar',
			'sLengthMenu':	'Mostrar <select>' +
				'<option value="10">10</option>'+
		        '<option value="20">20</option>'+
		        '<option value="30">30</option>'+
		        '<option value="40">40</option>'+
		        '<option value="50">50</option>'+
		        //'<option value="-1">Todos</option>'+
		        '</select> reservas'
			},
		'aaSorting':[[0,'desc']],	// or 'asc'
		'bJQueryUI':		true,	// enable jqueryUI Themes
		'bPaginate':		true,
		'bSort':			true,
		'bInfo':			true,
		'bAutoWidth':		true,
		'bProcessing': 		false,	
		'bServerSide': 		false	// use server side processing
	};

	oTable.dataTable(tableProperties);

	oTable.fnSort([[4,'desc']]);

	// TABLE ROW CLICK
	oTable.find('tbody tr').live('click', function() {

		if ( $(this).hasClass('row_selected') ) { // ... the row is already selected
			
			reserveInfo.empty();
			
            $(this).removeClass('row_selected'); 
            
            return;
		}
		else {
			
           	oTable.$('tr.row_selected').removeClass('row_selected');
           	
            $(this).addClass('row_selected');
		}
		
		var clientData = oTable.fnGetData(this);
		
		//console.log(clientData);

		if (!clientData)
			return;
		
		dataRequest = {
			classId: clientData.classID	
		};
		
		reserveInfo.empty();
		
		//reserveInfo.attr('title','datas');
		
		$.ajax({
			url: 		window.ajaxUrl + '/getScheduleInfo',
			async: 		true, 
			data: 		{ data: dataRequest},
			type: 		'POST',
			dataType: 	'json',
			success: 	function(schedules) {
				
				$.each(schedules, function(key, value) {
					var cal_container = '<div class="cal-container"><div class="cal-class-label inside-cal-container"><p>Aula '+ (key+1) + ':</p></div> <div class="cal-data-container inside-cal-container"><div class="cal-date-label"><p>Inicio:</p></div><div class="cal-date"><p>' + schedules[key].start +'</p></div><div class="cal-date-label"><p>Fim:</p></div><div class="cal-date"><p>' + schedules[key].end + '</div></p></div></div>';
					$(cal_container).appendTo(reserveInfo);
				});
			}
		});
		
		return;

		// dialog properties
		var opt = {
			width:		480,
			height:		400,
			show: 		'fade',
			hide: 		'fade',
			buttons: {
				"Ok": 		
				function() {
					$(this).dialog("close");
				}
			}
		};
		
		reserveInfo.dialog(opt);
	});
}






/**
 * Function with form filter configurations
 */
function formFilters() {
	
	// reference to datatable
	var oTable = $('#reservationTable').dataTable();
	
	// fill the first dropdown list with all available offers
	getAvailableOffers();

	// datepickers ...  
	var datePickerOpt = {
		dateFormat: 		'yy-mm-dd'
	};
	
	var startDate 	= $('#startDate');
	var endDate 	= $('#endDate');
	
	startDate.datepicker(datePickerOpt);
	endDate.datepicker(datePickerOpt);
	
	$('#offerList').change(function() {
		
		offerId = $(this).val();
		reserve = $('#reservationType').val();
		
		// reload
		oTable.fnReloadAjax();
	});

	startDate.change(function() {
		if(endDate.val()) {
			
			// set global vars to be used with datatable plugin
			offerId = $('#offerList').val();
			start 	= $(this).val();
			end 	= endDate.val();
			
			// reload datatable
			oTable.fnReloadAjax();
		}
	});
	
	endDate.change(function() {
		if(startDate.val()) {
			
			// set data
			offerId = $('#offerList').val();
			start 	= startDate.val();
			end 	= $(this).val();
			
			// ... reload
			oTable.fnReloadAjax();
		}
	});

	// button to clear date fields
	var clearButton = $('#clearButton');
	clearButton.button();
	clearButton.click(function() {
		startDate.val('');
		endDate.val('');
		offerId = $('#offerList').val();
		start 	= null;
		end 	= null;
		oTable.fnReloadAjax();
	});
}




/**
 * ... 
 */
function tmp() {
	
		
}




/**
 * function to draw the dialog to hold client reservation info
 */
function showInfoDialog(data) {
	
	var reserveInfo = $('#reserveInfo');
	
	reserveInfo.empty();
	
	reserveInfo.attr('title',data.clientID);
	
	// dialog properties
	var opt = {
		width:		480,
		height:		400,
		show: 		'fade',
		hide: 		'fade',
		buttons: {
			"Ok": 		
			function() {
				$(this).dialog("close");
			}
		}
	};
	
	reserveInfo.dialog(opt);
}






/**
 * function to fill the dropdown menu with the all offers
 */
function getAvailableOffers() {
	$.getJSON(window.ajaxUrl + "/allOffers", function(data) {
		if (!data) {
			
		}
		else {
			// ... holds data to be placed in the 'select' tag
			var options = '';
			
			for (var i = 0 ; i < data.length ; i++) {
				options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
			}
			
			// append the values between the 'select' tags present inside the id selector 'offerList'
			$("select#offerList").append(options);
		}
	});	
}

